// logger/logger.service.ts
import { resolve } from 'path';
import { createLogger, format, transports } from 'winston';
import 'winston-daily-rotate-file';
import { logDest } from '../constant/constant';
import { Logger } from 'typeorm';
// import util2 from 'node:util';
// eslint-disable-next-line @typescript-eslint/no-require-imports
// const util = require('node:util');

// const customFormat = format.printf(
//   ({ level, message, timestamp, stack, ...rest }) => {
//     let logMessage = `${timestamp} ${level}: `;

//     // 处理消息，如果是对象则进行序列化
//     if (typeof message === 'object') {
//       logMessage += util.inspect(message, {
//         depth: null,
//         colors: false,
//         compact: true,
//         breakLength: Infinity,
//       });
//     } else {
//       logMessage += message;
//     }

//     // 添加其他属性
//     if (Object.keys(rest).length > 0) {
//       logMessage += `\nAdditional Info: ${util.inspect(rest, {
//         depth: null,
//         colors: false,
//         compact: true,
//         breakLength: Infinity,
//       })}`;
//     }

//     // 添加错误堆栈（如果存在）
//     if (stack) {
//       logMessage += `\nStack Trace:\n${stack}`;
//     }

//     return logMessage;
//   },
// );
const logLevel = process.env.NODE_ENV === 'production' ? 'info' : 'debug';
const customFormat = format.combine(
  format.timestamp({
    format: 'YYYY-MM-DD HH:mm:ss',
  }),
  format.errors({ stack: true }),
  // format.splat(),
  format.printf(({ level, message, timestamp, ...metadata }) => {
    let msg = `${timestamp} [${level.toUpperCase()}]: ${JSON.stringify(message, null)}`;
    if (Object.keys(metadata).length > 0) {
      msg += '\n' + JSON.stringify(metadata, null);
    }
    return msg;
  }),
);

const logger = createLogger({
  level: logLevel,
  format: customFormat,
  transports: [
    new transports.DailyRotateFile({
      filename: resolve(logDest, 'info/info-%DATE%.log'),
      datePattern: 'YYYY-MM-DD',
      zippedArchive: true,
      maxSize: '20m',
      maxFiles: '30d',
      dirname: resolve(logDest, 'info'),
      level: 'info',
    }),
    new transports.DailyRotateFile({
      filename: resolve(logDest, 'error/error-%DATE%.log'),
      datePattern: 'YYYY-MM-DD',
      zippedArchive: true,
      maxSize: '20m',
      maxFiles: '30d',
      dirname: resolve(logDest, 'error'),
      level: 'error',
    }),
  ],
});

if (process.env.NODE_ENV !== 'production') {
  logger.add(
    new transports.Console({
      format: customFormat,
      level: 'debug',
    }),
  );
}

// 自定义 TypeORM 日志类
export class CustomTypeORMLogger implements Logger {
  logQuery(query: string, parameters?: any[]) {
    // logger.debug(
    //   `Query: ${query}${parameters ? ` -- Parameters: ${JSON.stringify(parameters)}` : ''}`,
    // );
  }

  logQueryError(error: string | Error, query: string, parameters?: any[]) {
    logger.error(
      `Query Error: ${error}${query ? ` -- Query: ${query}` : ''}${parameters ? ` -- Parameters: ${JSON.stringify(parameters)}` : ''}`,
    );
  }

  logQuerySlow(time: number, query: string, parameters?: any[]) {
    logger.error(
      `Slow Query (${time}ms): ${query}${parameters ? ` -- Parameters: ${JSON.stringify(parameters)}` : ''}`,
    );
  }

  logSchemaBuild(message: string) {
    logger.info(`Schema Build: ${message}`);
  }

  logMigration(message: string) {
    logger.info(`Migration: ${message}`);
  }

  log(level: 'log' | 'info' | 'warn', message: any) {
    switch (level) {
      case 'log':
      case 'info':
        logger.info(message);
        break;
      case 'warn':
        logger.warn(message);
        break;
    }
  }
}

export default logger;
